package com.yy.permissions_general.common.config.exception;

import com.yy.permissions_general.common.constant.StatusEnum;
import com.yy.permissions_general.common.config.exception.base.ServiceException;
import com.yy.permissions_general.utils.ResultUtil;
import com.yy.permissions_general.utils.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName GlobalExceptionHandler
 * @Description: TODO 全局的异常拦截器
 * @Author YangYI
 * @Date 2021/3/24
 * @Version V1.0
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(Exception.class)
    public ResultUtil handleRRException(Exception e) {
        log.error("系统异常,{}", e);
        return ResultUtil.error(e.getMessage());
    }

    /**
     * 拦截业务异常，返回业务异常信息
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public ResultUtil handleServiceError(ServiceException e) {
        return ResultUtil.error(e.getCode(),e.getMsg());
    }

    /**
     * 空指针异常
     * @param e NullPointerException
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    public ResultUtil handleTypeMismatchException(NullPointerException e) {
        log.error("空指针异常,{}", e.getMessage());
        return ResultUtil.error("空指针异常~");
    }

    /**
     * 参数异常
     * @param ex HttpMessageNotReadableException
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResultUtil handleHttpMessageNotReadableException(
            MissingServletRequestParameterException ex) {
        log.error("参数异常,{}", ex.getMessage());
        return ResultUtil.error(StatusEnum.PARAMETER_EXCEPTION.code,StatusEnum.PARAMETER_EXCEPTION.msg);
    }

    /**
     * 权 限 异 常 处 理
     */
    @ExceptionHandler({AccessDeniedException.class})
    public Object access(HttpServletRequest request, AccessDeniedException e) {
        e.printStackTrace();
        if (ServletUtil.isAjax(request)) {
            return ResultUtil.error(StatusEnum.NO_PERMISSION_ERROR);
        } else {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("/error/403");
            return modelAndView;
        }
    }

}
